package com.anos.smsfun.services;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;

import com.anos.smsfun.R;
import com.anos.smsfun.activities.ViewSmsConversationActivity;
import com.anos.smsfun.cache.AppConfigs;
import com.anos.smsfun.cache.SMSFunDataCache;
import com.anos.smsfun.model.ContactsWrapper;
import com.anos.smsfun.utility.DefConstants;
import com.anos.smsfun.utility.Utils;

public class SMSReceiver extends BroadcastReceiver {

	private static final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

	private AppConfigs mAppConfigs;

	@Override
	public void onReceive(Context context, Intent intent) {
		// Retrieves a map of extended data from the intent.
		if (intent.getAction().equals(ACTION_SMS_RECEIVED)) {
			final Bundle bundle = intent.getExtras();
			try {
				if (bundle != null) {
					final Object[] pdusObj = (Object[]) bundle.get("pdus");

					for (int i = 0; i < pdusObj.length; i++) {
						SmsMessage currentMessage = SmsMessage
								.createFromPdu((byte[]) pdusObj[i]);
						String phoneNumber = Utils
								.converStandardNumber(currentMessage
										.getDisplayOriginatingAddress());
						String message = currentMessage.getDisplayMessageBody();

						// Show Alert
						// Toast.makeText(context,
						// "Message received from: " + phoneNumber,
						// Toast.LENGTH_SHORT).show();
						
//						showPopup(context, phoneNumber, message);
//						Intent intentPopup = new Intent(context, DialogNotifiActivity.class);
//						intentPopup.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						context.startActivity(intentPopup);

						// notification
						showNotificationNewSMS(context, phoneNumber, message);

						// update badge
						mAppConfigs = AppConfigs.getInstance(context);
						int count = mAppConfigs.getNotifiCount() + 1;
						mAppConfigs.setNotifiCount(count);
						Utils.setBadge(context, count);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Notification show new message
	 * 
	 */
	@SuppressWarnings("deprecation")
	private void showNotificationNewSMS(Context context, String phoneNumber,
			String message) {
		String ns = Context.NOTIFICATION_SERVICE;
		NotificationManager mNotificationManager = (NotificationManager) context
				.getSystemService(ns);

		int icon = R.drawable.ic_main;
		String nameString = phoneNumber;
		ContactsWrapper contact = null;
		try {
			contact = SMSFunDataCache.getInstance(context).getContactDetail(
					phoneNumber);
		} catch (Exception e) {
		}
		if (contact != null)
			nameString = contact.getDisplayName();
		CharSequence tickerText = "SMS[" + nameString + "] - " + message;
		long when = System.currentTimeMillis();
		CharSequence contentTitle = "" + nameString;
		CharSequence contentText = message;

		Intent notificationIntent = new Intent(context,
				ViewSmsConversationActivity.class);
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		notificationIntent.putExtra(DefConstants.ACTION_VIEW_CONVERSATION,
				phoneNumber);

		PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
				notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

		Notification notification = new Notification(icon, tickerText, when);

		notification.setLatestEventInfo(context, contentTitle, contentText,
				contentIntent);
		notification.defaults |= Notification.DEFAULT_SOUND;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;// hide after its
															// selected

		mNotificationManager.notify(DefConstants.ID_NOTIFICATION_RECEIVED,
				notification);

	}

	/**
	 * show popup window
	 * 
	 */
	private void showPopup(Context context, String phoneNumber, String message) {
		String nameString = phoneNumber;
		ContactsWrapper contact = null;
		try {
			contact = SMSFunDataCache.getInstance(context).getContactDetail(
					phoneNumber);
		} catch (Exception e) {
		}
		if (contact != null)
			nameString = contact.getDisplayName();

		Builder builder = new Builder(context.getApplicationContext());
		builder.setTitle("[SMS] " + nameString);
		builder.setMessage(message);
		builder.setPositiveButton(
				context.getResources().getString(R.string.view),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						dialog.dismiss();
					}
				});
		builder.setNegativeButton(
				context.getResources().getString(R.string.close),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int arg1) {
						dialog.dismiss();
					}
				});

		AlertDialog dialog = builder.create();
		dialog.show();
	}
}
